package com.zy.fee.roadpark.activity.nb;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import com.flyco.roundview.RoundTextView;
import com.zy.fee.roadpark.R;
import com.zy.fee.roadpark.config.Constants;
import com.zy.fee.roadpark.dao.NbNodeRecordLogic;
import com.zy.fee.roadpark.model.M_Node;
import com.zy.fee.roadpark.model.M_NodeRecord;
import com.zy.fee.roadpark.model.apimodel.APIM_NodeRecordInfo;
import com.zy.fee.roadpark.util.Printer;
import com.zy.fee.roadpark.view.CommonDialog;
import com.zygk.library.base.BaseActivity;
import com.zygk.library.util.Convert;
import com.zygk.library.util.DateTimeUtil;
import com.zygk.library.util.HttpRequest;
import com.zygk.library.util.LibraryHelper;
import com.zygk.library.util.PreferencesHelper;
import com.zygk.library.util.StringUtils;
import com.zygk.library.util.ToastUtil;
import com.zygk.library.view.AutoResizeTextView;
import com.zygk.library.view.XKeyboardView;
import com.zygk.library.view.gridpasswordview.GridPasswordView;

/**
 * Created by Wikison on 2019/4/3.
 * 收款
 */
public class NbNodeReceivablesActivity extends BaseActivity {
  public static final String INTENT_NODE_RECORD = "INTENT_NODE_RECORD";
  public static final String INTENT_MONTH_MIN = "INTENT_MONTH_MIN";

  @BindView(R.id.tv_right) TextView tvRight;
  @BindView(R.id.ll_right) LinearLayout llRight;
  @BindView(R.id.lh_tv_title) TextView lhTvTitle;
  @BindView(R.id.et_code) EditText etCode;
  @BindView(R.id.gpvPlateNumber) GridPasswordView gpvPlateNumber;
  @BindView(R.id.iv_photo) ImageView ivPhoto;
  @BindView(R.id.tv_time) AutoResizeTextView tvTime;
  @BindView(R.id.tv_money) TextView tvMoney;
  @BindView(R.id.iv_code) ImageView ivCode;
  @BindView(R.id.rtv_receive) RoundTextView rtvReceive;
  @BindView(R.id.view_keyboard) XKeyboardView viewKeyboard;
  @BindView(R.id.tv_print) TextView tvPrint;
  @BindView(R.id.ll_month_info) LinearLayout llMonthInfo;
  @BindView(R.id.tv_month_day) TextView tvMonthDay;
  @BindView(R.id.tv_month_left) TextView tvMonthLeft;

  private M_Node mNode;
  private M_NodeRecord nodeRecord;
  private boolean reRegistration = false; //是否重新取证

  @Override protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ButterKnife.bind(this);
  }

  @Override public void setContentView() {
    setContentView(R.layout.activity_nb_node_receivables);
  }

  @Override public void init() {
    initData();
    initView();
    initListener();
  }

  private void initData() {
    registerReceiver(new String[] { Constants.BROADCAST_FORENSICS_SUCCESS });

    mNode = (M_Node) getIntent().getSerializableExtra(NbSpotListActivity.INTENT_NODE);

    nbnode_searchRecord_unPay();
  }

  private void initView() {
    lhTvTitle.setText("收款");
    llRight.setVisibility(View.VISIBLE);
    tvRight.setText("重新取证");
    tvPrint.setVisibility(View.VISIBLE);

    etCode.setText(mNode.getCode());
    etCode.setEnabled(false);
    gpvPlateNumber.setPassword(mNode.getCarNumber());
    gpvPlateNumber.setEnabled(false);

    if (mNode.getIsMonth() == 1) {
      llMonthInfo.setVisibility(View.VISIBLE);
      tvMonthDay.setText(
          "包月到期: " + DateTimeUtil.getDateByAddMinute(mNode.getStartTime(), mNode.getMonthMin())
              .substring(0, 10));
      tvMonthLeft.setText("包月剩余: " + mNode.getMonthMin() / 1440 + "天");
    } else {
      llMonthInfo.setVisibility(View.GONE);
    }
  }

  private void initListener() {
    viewKeyboard.setIOnKeyboardListener(new XKeyboardView.IOnKeyboardListener() {
      @Override public void onInsertKeyEvent(String text) {
        gpvPlateNumber.appendPassword(text);
      }

      @Override public void onDeleteKeyEvent() {
        gpvPlateNumber.deletePassword();
      }
    });

    gpvPlateNumber.togglePasswordVisibility();

    gpvPlateNumber.setOnPasswordChangedListener(new GridPasswordView.OnPasswordChangedListener() {
      @Override public boolean beforeInput(int position) {
        viewKeyboard.setVisibility(View.GONE);
        return true;
      }

      @Override public void onTextChanged(String psw) {
      }

      @Override public void onInputFinish(String psw) {
      }
    });
  }

  private void printTicket() {
    if (null == nodeRecord) {
      ToastUtil.showMessage(mContext, "没有缴费停车单");
      return;
    }

    try {
      Printer.printT(nodeRecord.getCarNumber(), nodeRecord.getStartTime(), Constants.PAY_NB_URL + nodeRecord.getNodeRecordID(), false, preferencesHelper.getSettingString(PreferencesHelper.User.Key.LOT_ID));
      nbnode_record_pay_admin();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  private void printForensicsTicket() {
    if (null == nodeRecord) {
      ToastUtil.showMessage(mContext, "没有缴费停车单");
      return;
    }

    try {
      Printer.printT(nodeRecord.getCarNumber(), (StringUtils.isBlank(mNode.getStartTime()) ? DateTimeUtil.getCurrentTime()
        : mNode.getStartTime()), Constants.PAY_NB_URL + nodeRecord.getNodeRecordID(), false, preferencesHelper.getSettingString(PreferencesHelper.User.Key.LOT_ID));
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  private void nbnode_searchRecord_unPay() {
    NbNodeRecordLogic.nbnode_searchrecord_unpay(mContext, LibraryHelper.userManager().getUserID(),
        mNode.getCode(), mNode.getCarNumber(), new HttpRequest.HttpCallback() {
          @Override public void onStart() {
            showNoCancelPd();
          }

          @Override public void onSucceed(Object obj) {
            APIM_NodeRecordInfo result = (APIM_NodeRecordInfo) obj;
            if (result.getIsFind() == 1) {
              nodeRecord = result.getNodeRecordInfo();
              imageManager.loadUrlImage(nodeRecord.getPic(), ivPhoto);
              tvMoney.setText(Convert.getMoneyString(nodeRecord.getMoney()));
              tvTime.setText(DateTimeUtil.getMinutesFormat(nodeRecord.getMin()));
            } else {
              ToastUtil.showMessage(mContext, "未找到停车单");
            }
          }

          @Override public void onFailed() {
            ToastUtil.showNetErrorMessage(mContext);
          }

          @Override public void onFinish() {
            dismissPd();
          }
        });
  }

  private void nbnode_record_pay_admin() {
    NbNodeRecordLogic.nbnode_record_pay_admin(mContext, LibraryHelper.userManager().getUserID(),
        nodeRecord.getNodeRecordID(), new HttpRequest.HttpCallback() {
          @Override public void onStart() {
            showNoCancelPd();
          }

          @Override public void onSucceed(Object obj) {
            sendBroadcast(new Intent(Constants.BROADCAST_REFRESH_NODE_LIST));
            ToastUtil.showMessage(mContext, "已完成收款");
            finish();
          }

          @Override public void onFailed() {
            ToastUtil.showNetErrorMessage(mContext);
          }

          @Override public void onFinish() {
            dismissPd();
          }
        });
  }

  private void nbnode_record_end() {
    NbNodeRecordLogic.nbnode_record_end(mContext, nodeRecord.getNodeRecordID(),
        new HttpRequest.HttpCallback() {
          @Override public void onStart() {
            showNoCancelPd();
          }

          @Override public void onSucceed(Object obj) {
            sendBroadcast(new Intent(Constants.BROADCAST_REFRESH_NODE_LIST));
            ToastUtil.showMessage(mContext, "结束订单成功");
            finish();
          }

          @Override public void onFailed() {

          }

          @Override public void onFinish() {
            dismissPd();
          }
        });
  }

  @Override protected void handleReceiver(Context context, Intent intent) {
    super.handleReceiver(context, intent);
    if (intent == null || TextUtils.isEmpty(intent.getAction())) {
      return;
    }
    if (Constants.BROADCAST_FORENSICS_SUCCESS.equals(intent.getAction())) {
      finish();
    }
  }

  @OnClick({
      R.id.ll_back, R.id.ll_right, R.id.tv_print, R.id.iv_code, R.id.rtv_receive, R.id.rtv_pay, R.id.rtv_complete
  })
  public void onViewClicked(View view) {
    switch (view.getId()) {
      case R.id.ll_back:
        finish();
        break;
      case R.id.ll_right:
        Intent intent = new Intent(mContext, NbRegistrationPlateActivity.class);
        intent.putExtra(NbSpotListActivity.INTENT_NODE, mNode);
        intent.putExtra(NbRegistrationPlateActivity.INTENT_IS_FORENSIC, true);
        intent.putExtra(NbRegistrationPlateActivity.INTENT_ORIGIN_PLATE, mNode.getCarNumber());
        startActivity(intent);
        break;
      case R.id.tv_print:
        printForensicsTicket();
        break;
      case R.id.iv_code:
      case R.id.rtv_pay:
        if (null == nodeRecord) {
          ToastUtil.showMessage(mContext, "未找到停车单");
          return;
        }
        if (!StringUtils.isBlank(nodeRecord.getNodeRecordID())) {
          CommonDialog.showQrCodeDialog(mContext,
              Constants.PAY_NB_URL + nodeRecord.getNodeRecordID());
        }
        break;
      case R.id.rtv_receive:
        CommonDialog.showYesOrNoDialog(mContext, "确定完成现金收款吗?", "取消", "确定", () -> {
          printTicket();
        }, () -> {
        });
        break;
      case R.id.rtv_complete:
        CommonDialog.showStopOrderDialog(mContext, "确定结束订单吗?", () -> {
          nbnode_record_end();
        }, () -> {
          Intent intent1 = new Intent(mContext, NbForensicsAddActivity.class);
          intent1.putExtra(INTENT_NODE_RECORD, nodeRecord);
          startActivity(intent1);
        }, () -> {
        });
        break;
    }
  }

  @Override protected void onDestroy() {
    super.onDestroy();
  }
}
